package com.example.springboot3.config;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;

import java.util.Locale;

/**
 * @author 张琪
 * @date 2024-02-21 15:29
 */
@Configuration
public class MyLocaleResolve implements LocaleResolver {

    /**
     * 注入 HttpServletRequest
     */
    @Resource
    private HttpServletRequest request;

    public Locale getLocale() {
        return resolveLocale(request);
    }

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        //获取请求中的语言参数
        String language = request.getParameter("lang");
        //如果没有就使用默认的（根据主机的语言环境生成一个 Locale
        Locale locale = Locale.getDefault();
        //如果请求的链接中携带了 国际化的参数
        if (StringUtils.isNotEmpty(language)){
            //zh_CN
            String[] s = language.split("-");
            //国家，地区
            locale = new Locale(s[0], s[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}
